package com.qst.servlet;

import com.alibaba.fastjson.JSON;
import com.qst.biz.MenuBiz;
import com.qst.biz.impl.MenuBizImpl;
import com.qst.common.StateConstaint;
import com.qst.entity.Menu;
import com.qst.entity.User;
import com.qst.utils.HttpResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(
        name = "MenuGetByRoleIDServlet",
        urlPatterns = "/api/menu/getByRoleID"
)
public class MenuGetByRoleIDServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        Object loginUser2 = req.getSession().getAttribute("loginUser");
        User loginUser = null;
        if (loginUser2 instanceof User){
            loginUser= (User) loginUser;
        }
        MenuBiz menuBiz=new MenuBizImpl();
        List<Menu> menuByRole = menuBiz.getMenuByRole(loginUser.getRole().getRoleID());
        HttpResult<List<Menu>> httpResult=new HttpResult<>();
        if (menuByRole!=null && menuByRole.size()>0){
            httpResult.setData(menuByRole);
            httpResult.setCode(StateConstaint.DATA_OK);
            httpResult.setMsg("success");
        }else{
            httpResult.setData(null);
            httpResult.setMsg("没有获取到菜单列表");
            httpResult.setCode(StateConstaint.DATA_NOT_FOUND);
        }

        String content = JSON.toJSONString(httpResult);
        System.out.println(content);
        PrintWriter out = resp.getWriter();

        out.write(content);
        out.flush();
        out.close();

    }
}
